package cn.itcast.service.impl;

import cn.itcast.entity.PageResult;
import cn.itcast.entity.QueryPageBean;
import cn.itcast.mapper.MemberMapper;
import cn.itcast.pojo.Member;
import cn.itcast.pojo.User;
import cn.itcast.service.MemberService;
import cn.itcast.utils.MD5Utils;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service(interfaceClass = MemberService.class)
public class MemberServiceImpl implements MemberService {

    @Autowired
    MemberMapper mapper;

    public Member findByTelephone(String telephone) {

        return mapper.findByTelephone(telephone);
    }


    @Transactional
    public void add(Map map) {
        //获取密码
        Object obj = map.get("password");

        if(obj!=null) {
            String pwd = obj.toString();
            //判断密码是否存在
            if(pwd != null && pwd.length() > 0) {
                //完成md5加密
                String s = MD5Utils.md5(pwd);
                //将加密后的密码重新加载进map
                map.put("password", s);
            }
        }
        mapper.add(map);
    }



    public List<Integer> findMemberCountByMonths(List<String> months) {

        return mapper.findMemberCountBeforeDate_2(months);
    }


    public PageResult queryPage(QueryPageBean queryPageBean) {
        //pageHelper.starpage(当前页码，每页展示条数)
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());

        //将查寻出的结果封装为集合对象
        List<Member> list = mapper.selectByCondition(queryPageBean.getQueryString());

        //将集合载入到pageInfo中，反推出总页数
        PageInfo pi = new PageInfo(list);

        //将总页数与当前页集合载入到PageResult进行返回
        PageResult result = new PageResult(pi.getTotal(),list);

        return result;
    }


    public void deleteById(int id) {
        mapper.deleteById(id);
    }


    public Member findById(int id) {
        return mapper.findById(id);
    }


    public void edit(Member member) {
        mapper.edit(member);
    }

    @Override
    public List<Member> findAll() {
        return mapper.findAll();
    }

    @Override
    public List<User> getAddress() {
        return mapper.getAddress();
    }

    @Override
    public List<Map<String, Object>> findEvery() {
        return mapper.findEvery();
    }
}
